package com.utooo.service.purchase;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.constant.ResultCodeConstant;
import com.utooo.dao.purchase.ContractAcceptanceDetailMapper;
import com.utooo.dao.purchase.ContractAcceptanceMapper;
import com.utooo.dao.purchase.SupplierContractAcceptanceMapper;
import com.utooo.pojo.domain.purchase.contract.ContractAcceptanceDO;
import com.utooo.pojo.domain.purchase.contract.ContractAcceptanceDetailDO;
import com.utooo.pojo.domain.purchase.contract.PurchaseContractDO;
import com.utooo.pojo.domain.supplier.settlement.SupplierContractAcceptanceDO;
import com.utooo.pojo.dto.common.RestResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

@Service
@Slf4j
@RequiredArgsConstructor
public class ContractAcceptanceServiceImpl extends ServiceImpl<ContractAcceptanceMapper, ContractAcceptanceDO>
        implements ContractAcceptanceService {

    private final PurchaseContractService purchaseContractService;
    private final ContractAcceptanceDetailMapper acceptanceDetailMapper;
    private final SupplierContractAcceptanceMapper supplierContractAcceptanceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<String> addContractAcceptance(String contractId) {
        PurchaseContractDO purchaseContract = purchaseContractService.getById(contractId);
        if (purchaseContract == null) {
            log.error("采购合同不存在，id:{}", contractId);
            return new RestResult<>(ResultCodeConstant.CODE_200, "采购合同不存在");
        }
        ContractAcceptanceDO contractAcceptance = new ContractAcceptanceDO();
        BeanUtil.copyProperties(purchaseContract, contractAcceptance, IGNORED_PROPERTIES);
        contractAcceptance.setAcceptanceNo(generateAcceptanceNo());
        contractAcceptance.setApplicationDate(purchaseContract.getCreateTime());
        contractAcceptance.setContractNo(contractId);
        contractAcceptance.setStatus("1");
        this.save(contractAcceptance);

        ContractAcceptanceDetailDO contractAcceptanceDetail = new ContractAcceptanceDetailDO();
        contractAcceptanceDetail.setContractNo(contractId);
        contractAcceptanceDetail.setContractName(purchaseContract.getTitle());
        contractAcceptanceDetail.setForeignId(contractAcceptance.getId());
        acceptanceDetailMapper.insert(contractAcceptanceDetail);
        return new RestResult<>(ResultCodeConstant.CODE_200, ResultCodeConstant.CODE_200_MSG);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<String> confirmAndSyncContractAcceptance(String id) {
        ContractAcceptanceDO acceptance = this.getById(id);
        if (acceptance == null) {
            log.error("验收单不存在，id:{}", id);
            return new RestResult<>(ResultCodeConstant.CODE_400, "验收单不存在");
        }
        SupplierContractAcceptanceDO supplierContractAcceptance =
                supplierContractAcceptanceMapper.selectOne(new LambdaQueryWrapper<SupplierContractAcceptanceDO>()
                        .eq(SupplierContractAcceptanceDO::getContractAcceptanceId, id));
        if (supplierContractAcceptance != null) {
            log.error("验收单已同步，id:{}", id);
            return new RestResult<>(ResultCodeConstant.CODE_400, "该验收单已确认，无需重复确认！");
        }
        // 待供应商确认
        acceptance.setStatus("2");
        this.updateById(acceptance);
        supplierContractAcceptance = new SupplierContractAcceptanceDO();
        BeanUtil.copyProperties(acceptance, supplierContractAcceptance, IGNORED_PROPERTIES);
        supplierContractAcceptance.setContractAcceptanceId(id);
        supplierContractAcceptanceMapper.insert(supplierContractAcceptance);
        String acceptanceId = supplierContractAcceptance.getId();
        List<ContractAcceptanceDetailDO> details = acceptanceDetailMapper
                .selectList(new LambdaQueryWrapper<ContractAcceptanceDetailDO>()
                        .eq(ContractAcceptanceDetailDO::getForeignId, id));
        if (CollUtil.isNotEmpty(details)) {
            CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(IGNORED_PROPERTIES);
            List<ContractAcceptanceDetailDO> contractAcceptanceDetails =
                    BeanUtil.copyToList(details, ContractAcceptanceDetailDO.class, copyOptions);
            contractAcceptanceDetails.forEach(i -> i.setForeignId(acceptanceId));
            acceptanceDetailMapper.insert(contractAcceptanceDetails);
        }
        return new RestResult<>(ResultCodeConstant.CODE_200, ResultCodeConstant.CODE_200_MSG);
    }

    private String generateAcceptanceNo() {
        String prefix = "YS";
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<ContractAcceptanceDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(ContractAcceptanceDO::getAcceptanceNo, prefix + datePart);
        queryWrapper.orderByDesc(ContractAcceptanceDO::getAcceptanceNo);
        queryWrapper.last("LIMIT 1");
        ContractAcceptanceDO orderInventoryDO = this.getOne(queryWrapper);

        // 生成序列号
        int maxSequence = 0;
        if (orderInventoryDO != null) {
            String acceptanceNo = orderInventoryDO.getAcceptanceNo();
            maxSequence = Integer.parseInt(acceptanceNo.substring((prefix + datePart).length()));
        }
        int nextSequence = maxSequence + 1;
        String sequencePart = String.format("%03d", nextSequence);
        return prefix + datePart + sequencePart;
    }

}